package cc.mrbird.febs.common.controller;

import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.system.entity.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.HashMap;
import java.util.Map;

/**
 * @author MrBird
 */
public class BaseController {

    private Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    protected User getCurrentUser() {
        return (User) getSubject().getPrincipal();
    }

    protected Session getSession() {
        return getSubject().getSession();
    }

    protected Session getSession(Boolean flag) {
        return getSubject().getSession(flag);
    }

    protected void login(AuthenticationToken token) {
        getSubject().login(token);
    }

    protected Map<String, Object> getDataTable(IPage<?> pageInfo) {
        return getDataTable(pageInfo, FebsConstant.DATA_MAP_INITIAL_CAPACITY);
    }

    protected Map<String, Object> getDataTable(IPage<?> pageInfo, int dataMapInitialCapacity) {
        Map<String, Object> data = new HashMap<>(dataMapInitialCapacity);
        data.put("rows", pageInfo.getRecords());
        data.put("total", pageInfo.getTotal());
        return data;
    }

    /**
     * 根据查询的datatable  填充是否有上一页下一页当前页总数据条数数据
     * @param dataTable
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Map<String, Object> getInterfacePageData(Map<String, Object> dataTable,int pageNum,int pageSize){
        Integer total= Integer.parseInt(dataTable.get("total").toString());
        int totalPage=total/pageSize+1;
        if(totalPage>pageNum){
            dataTable.put("hasNext",true);
        }else{
            dataTable.put("hasNext",false);
        }
        if(pageNum>1){
            dataTable.put("hasPrevious",true);
        }else{
            dataTable.put("hasPrevious",false);
        }
        dataTable.put("totalPage",totalPage);//总页数
        dataTable.put("currentPage",pageNum);//当前页码
        dataTable.put("pageSize",pageSize);//每页数据量
        return dataTable;
    }

}
